package cn.dceast.former.service;

import cn.dceast.former.dao.EyeModelDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by fanbo on 2017-07-18.
 * 文件上传的Service
 */
@Service
public class FileDataService {
    @Autowired
    private EyeModelDataMapper eyeModelDataMapper;

    /**
     * 读取上传文件的数据进行动态表保存
     * @param dataList

     * @return
     */
    public String saveExcelData(List dataList) {
        String result = "";
        try {
            if(dataList!=null && dataList.size()>0) {
                String tableName = "upload_file_data_"+System.currentTimeMillis();

                Map map = new HashMap<>();
                map.put("tablename", tableName);
                //动态建表
                for(int i=0;i<dataList.size();i++) {
                    Object[] objects = (Object[]) dataList.get(i);
                    //表字段
                    String[] keys = new String[objects.length];
                    for (int j = 0; j < objects.length; j++) {
                        String key = "cloum" + j;
                        keys[j] = key;
                    }
                    if (i == 0) {
                        map.put("keys", keys);
                    }
                    break;
                }
                //动态生成表
                eyeModelDataMapper.creatTable(map);
                //动态存数据
                for(int i=0;i<dataList.size();i++) {
                    Object[] objects = (Object[]) dataList.get(i);
                    //表字段
                    Map<String, Object> params = new HashMap<>();
                    for (int j = 0; j < objects.length; j++) {
                        String key = "cloum" + j;
                        params.put(key,objects[j]);
                    }
                    map.put("params",params);
                    eyeModelDataMapper.insertDataToTable(map);
                }
                result = tableName;
            }else{
                result = "";
            }
            return  result;
        } catch (Exception e) {
            e.printStackTrace();
            result = "";
            return  result;
        }
    }


    /**
     * 删除表
     * @param className
     * @return
     */
    public Integer deleteTableByName(String className) {
        try {
            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("className",className);
            eyeModelDataMapper.deleteTableByName(paramMap);
            return  1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public void deleteContactInfoByTableName(String className) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("className",className);
        eyeModelDataMapper.deleteContactInfoByTableName(paramMap);
    }
}
